<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入商品编码" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable size="small">
          <el-option v-for="item in warehouseOptions" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleStockIn">入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-minus" size="mini" @click="handleStockOut">出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-refresh" size="mini" @click="handleAdjust">库存调整</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-set-up" size="mini" @click="handleSetAlert">设置预警</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-tickets" size="mini" @click="handleViewChanges">变动记录</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 预警信息提示 -->
    <el-alert
      v-if="alertList.length > 0"
      title="以下商品库存不足，请及时补充！"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;">
      <div v-for="(item, index) in alertList" :key="index">
        <span>{{ item.productName }} - {{ item.warehouseName }}: 当前库存 {{ item.quantity }} {{ item.unit }}，低于预警阈值 {{ item.alertThreshold }} {{ item.unit }}</span>
      </div>
    </el-alert>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编码" align="center" prop="productCode" width="120" />
      <el-table-column label="商品名称" align="center" prop="productName" width="180" />
      <el-table-column label="规格" align="center" prop="specification" width="120" />
      <el-table-column label="单位" align="center" prop="unit" width="80" />
      <el-table-column label="仓库" align="center" prop="warehouseName" width="120" />
      <el-table-column label="库存数量" align="center" prop="quantity" width="100">
        <template slot-scope="scope">
          <span :class="{'inventory-alert': scope.row.quantity <= scope.row.alertThreshold}">{{ scope.row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用数量" align="center" prop="availableQuantity" width="100" />
      <el-table-column label="锁定数量" align="center" prop="lockedQuantity" width="100" />
      <el-table-column label="预警阈值" align="center" prop="alertThreshold" width="100" />
      <el-table-column label="最后盘点时间" align="center" prop="lastCheckTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastCheckTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleStockInItem(scope.row)">入库</el-button>
          <el-button size="mini" type="text" icon="el-icon-minus" @click="handleStockOutItem(scope.row)">出库</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="handleViewItemChanges(scope.row)">变动记录</el-button>
          <el-button size="mini" type="text" icon="el-icon-set-up" @click="handleSetAlertItem(scope.row)">设置预警</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择商品" style="width: 100%;" @change="handleProductSelect" :disabled="form.isEdit">
            <el-option v-for="item in productOptions" :key="item.productId" :label="item.productName" :value="item.productId" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width: 100%;" :disabled="form.isEdit">
            <el-option v-for="item in warehouseOptions" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" v-if="form.isEdit">
          <span>{{ form.currentQuantity }} {{ form.unit }}</span>
        </el-form-item>
        <el-form-item :label="operateTypeLabel" prop="quantity">
          <el-input-number v-model="form.quantity" :min="operateType === 'stockOut' ? 1 : operateType === 'adjust' ? -999 : 1" :precision="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置预警对话框 -->
    <el-dialog title="设置库存预警阈值" :visible.sync="alertOpen" width="500px" append-to-body>
      <el-form ref="alertForm" :model="alertForm" :rules="alertRules" label-width="80px">
        <el-form-item label="商品">
          <span>{{ alertForm.productName }}</span>
        </el-form-item>
        <el-form-item label="仓库">
          <span>{{ alertForm.warehouseName }}</span>
        </el-form-item>
        <el-form-item label="预警阈值" prop="alertThreshold">
          <el-input-number v-model="alertForm.alertThreshold" :min="0" :precision="0" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAlertForm">确 定</el-button>
        <el-button @click="alertOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 库存变动记录对话框 -->
    <el-dialog :title="changeTitle" :visible.sync="changeOpen" width="900px" append-to-body>
      <el-form :inline="true" :model="changeQueryParams" class="demo-form-inline">
        <el-form-item label="商品">
          <el-select v-model="changeQueryParams.productId" placeholder="请选择商品" clearable>
            <el-option v-for="item in productOptions" :key="item.productId" :label="item.productName" :value="item.productId" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="changeQueryParams.warehouseId" placeholder="请选择仓库" clearable>
            <el-option v-for="item in warehouseOptions" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="变动类型">
          <el-select v-model="changeQueryParams.changeType" placeholder="请选择变动类型" clearable>
            <el-option v-for="item in changeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getChangeList">查询</el-button>
          <el-button @click="resetChangeQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="changeList" style="width: 100%" v-loading="changeLoading">
        <el-table-column label="变动时间" prop="createTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品" prop="productName" width="150" />
        <el-table-column label="仓库" prop="warehouseName" width="120" />
        <el-table-column label="变动类型" prop="changeType" width="100">
          <template slot-scope="scope">
            <el-tag :type="changeTypeTag(scope.row.changeType)">{{ changeTypeText(scope.row.changeType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="变动前" prop="beforeQuantity" width="80" />
        <el-table-column label="变动数量" prop="changeQuantity" width="80">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.changeType === 1 || scope.row.changeType === 3 ? 'green' : 'red' }">
              {{ scope.row.changeType === 1 || scope.row.changeType === 3 ? '+' : '-' }}{{ scope.row.changeQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="变动后" prop="afterQuantity" width="80" />
        <el-table-column label="操作人" prop="operatorName" width="100" />
        <el-table-column label="备注" prop="remark" />
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="changeTotal>0"
        :total="changeTotal"
        :page.sync="changeQueryParams.pageNum"
        :limit.sync="changeQueryParams.pageSize"
        @pagination="getChangeList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, listAlert, stockIn, stockOut, adjustStock, setAlertThreshold } from "@/api/inventory/inventory";
import { listStockChange } from "@/api/inventory/stockChange";
import {listProduct} from "@/api/product";
import { listWarehouse } from "@/api/inventory/warehouse";

export default {
  name: "Inventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      inventoryList: [],
      // 预警库存列表
      alertList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        productCode: undefined,
        warehouseId: undefined
      },
      // 操作类型（入库、出库、调整）
      operateType: "stockIn",
      // 表单参数
      form: {
        productId: undefined,
        warehouseId: undefined,
        quantity: 1,
        remark: "",
        isEdit: false,
        currentQuantity: 0,
        unit: ""
      },
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "商品不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ]
      },
      // 商品选项
      productOptions: [],
      // 仓库选项
      warehouseOptions: [],
      // 设置预警对话框
      alertOpen: false,
      // 预警表单
      alertForm: {
        productId: undefined,
        productName: "",
        warehouseId: undefined,
        warehouseName: "",
        alertThreshold: 0
      },
      // 预警表单校验
      alertRules: {
        alertThreshold: [
          { required: true, message: "预警阈值不能为空", trigger: "blur" }
        ]
      },
      // 库存变动记录对话框
      changeOpen: false,
      // 变动记录标题
      changeTitle: "库存变动记录",
      // 变动记录加载状态
      changeLoading: false,
      // 变动记录列表
      changeList: [],
      // 变动记录总数
      changeTotal: 0,
      // 变动记录查询参数
      changeQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: undefined,
        warehouseId: undefined,
        changeType: undefined
      },
      // 变动类型选项
      changeTypeOptions: [
        { value: 1, label: "入库" },
        { value: 2, label: "出库" },
        { value: 3, label: "盘盈" },
        { value: 4, label: "盘亏" },
        { value: 5, label: "调拨" }
      ]
    };
  },
  computed: {
    // 操作类型标签
    operateTypeLabel() {
      if (this.operateType === "stockIn") return "入库数量";
      if (this.operateType === "stockOut") return "出库数量";
      if (this.operateType === "adjust") return "调整数量";
      return "数量";
    }
  },
  created() {
    this.getList();
    this.getAlertList();
    this.getProductOptions();
    this.getWarehouseOptions();
  },
  methods: {
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询预警库存列表 */
    getAlertList() {
      listAlert().then(response => {
        this.alertList = response.data;
      });
    },
    /** 获取商品选项 */
    getProductOptions() {
      listProduct().then(response => {
        this.productOptions = response.data;
      });
    },
    /** 获取仓库选项 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        this.warehouseOptions = response.data;
      });
    },
    // 变动类型标签样式
    changeTypeTag(type) {
      if (type === 1) return "success";
      if (type === 2) return "danger";
      if (type === 3) return "warning";
      if (type === 4) return "info";
      if (type === 5) return "primary";
      return "";
    },
    // 变动类型文本
    changeTypeText(type) {
      const option = this.changeTypeOptions.find(item => item.value === type);
      return option ? option.label : "";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: undefined,
        warehouseId: undefined,
        quantity: 1,
        remark: "",
        isEdit: false,
        currentQuantity: 0,
        unit: ""
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 入库按钮操作 */
    handleStockIn() {
      this.reset();
      this.operateType = "stockIn";
      this.title = "商品入库";
      this.open = true;
    },
    /** 出库按钮操作 */
    handleStockOut() {
      this.reset();
      this.operateType = "stockOut";
      this.title = "商品出库";
      this.open = true;
    },
    /** 库存调整按钮操作 */
    handleAdjust() {
      this.reset();
      this.operateType = "adjust";
      this.title = "库存调整";
      this.open = true;
    },
    /** 指定商品入库操作 */
    handleStockInItem(row) {
      this.reset();
      this.operateType = "stockIn";
      this.title = "商品入库";
      this.form.productId = row.productId;
      this.form.warehouseId = row.warehouseId;
      this.form.isEdit = true;
      this.form.currentQuantity = row.quantity;
      this.form.unit = row.unit;

      // 查找商品和仓库信息
      const product = this.productOptions.find(p => p.productId === row.productId);
      const warehouse = this.warehouseOptions.find(w => w.warehouseId === row.warehouseId);

      if (product && warehouse) {
        this.open = true;
      } else {
        this.$message.error("商品或仓库信息获取失败");
      }
    },
    /** 指定商品出库操作 */
    handleStockOutItem(row) {
      this.reset();
      this.operateType = "stockOut";
      this.title = "商品出库";
      this.form.productId = row.productId;
      this.form.warehouseId = row.warehouseId;
      this.form.isEdit = true;
      this.form.currentQuantity = row.quantity;
      this.form.unit = row.unit;

      // 查找商品和仓库信息
      const product = this.productOptions.find(p => p.productId === row.productId);
      const warehouse = this.warehouseOptions.find(w => w.warehouseId === row.warehouseId);

      if (product && warehouse) {
        this.open = true;
      } else {
        this.$message.error("商品或仓库信息获取失败");
      }
    },
    /** 选择商品回调 */
    handleProductSelect(productId) {
      const product = this.productOptions.find(p => p.productId === productId);
      if (product) {
        this.form.unit = product.unit;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const params = {
            productId: this.form.productId,
            warehouseId: this.form.warehouseId,
            quantity: this.form.quantity,
            remark: this.form.remark
          };

          if (this.operateType === "stockIn") {
            stockIn(params).then(response => {
              this.$modal.msgSuccess("入库操作成功");
              this.open = false;
              this.getList();
              this.getAlertList();
            });
          } else if (this.operateType === "stockOut") {
            stockOut(params).then(response => {
              this.$modal.msgSuccess("出库操作成功");
              this.open = false;
              this.getList();
              this.getAlertList();
            }).catch(err => {
              this.$message.error("出库失败，可能是库存不足");
            });
          } else if (this.operateType === "adjust") {
            adjustStock(params).then(response => {
              this.$modal.msgSuccess("库存调整成功");
              this.open = false;
              this.getList();
              this.getAlertList();
            }).catch(err => {
              this.$message.error("库存调整失败，请检查数量是否正确");
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`);
    },
    /** 设置预警阈值（批量） */
    handleSetAlert() {
      if (this.single) {
        this.$message.warning("请选择一条库存记录");
        return;
      }

      const row = this.inventoryList.find(item => item.inventoryId === this.ids[0]);
      this.handleSetAlertItem(row);
    },
    /** 设置预警阈值（单个） */
    handleSetAlertItem(row) {
      this.alertForm = {
        productId: row.productId,
        productName: row.productName,
        warehouseId: row.warehouseId,
        warehouseName: row.warehouseName,
        alertThreshold: row.alertThreshold || 0
      };
      this.alertOpen = true;
    },
    /** 提交预警设置 */
    submitAlertForm() {
      this.$refs["alertForm"].validate(valid => {
        if (valid) {
          const params = {
            productId: this.alertForm.productId,
            warehouseId: this.alertForm.warehouseId,
            alertThreshold: this.alertForm.alertThreshold
          };

          setAlertThreshold(params).then(response => {
            this.$modal.msgSuccess("预警阈值设置成功");
            this.alertOpen = false;
            this.getList();
            this.getAlertList();
          });
        }
      });
    },
    /** 查看库存变动记录 */
    handleViewChanges() {
      this.changeTitle = "库存变动记录";
      this.changeQueryParams = {
        pageNum: 1,
        pageSize: 10,
        productId: undefined,
        warehouseId: undefined,
        changeType: undefined
      };
      this.getChangeList();
      this.changeOpen = true;
    },
    /** 查看指定商品库存变动记录 */
    handleViewItemChanges(row) {
      this.changeTitle = `${row.productName} 库存变动记录`;
      this.changeQueryParams = {
        pageNum: 1,
        pageSize: 10,
        productId: row.productId,
        warehouseId: row.warehouseId,
        changeType: undefined
      };
      this.getChangeList();
      this.changeOpen = true;
    },
    /** 查询变动记录列表 */
    getChangeList() {
      this.changeLoading = true;
      listStockChange(this.changeQueryParams).then(response => {
        this.changeList = response.data;
        this.changeTotal = response.total;
        this.changeLoading = false;
      });
    },
    /** 重置变动记录查询条件 */
    resetChangeQuery() {
      this.changeQueryParams = {
        pageNum: 1,
        pageSize: 10,
        productId: undefined,
        warehouseId: undefined,
        changeType: undefined
      };
      this.getChangeList();
    }
  }
};
</script>

<style scoped>
.inventory-alert {
  color: #F56C6C;
  font-weight: bold;
}
</style>
